<template>
  <view class="login">
    <view class="backg h1000rpx w750rpx flex-col flex-center">
      <u-image :src="`${$url}/profile/upload/2024/11/18/logo@2x_20241118173344A006.png`" />
      <view class="mt10rpx box-border wfull p30rpx">
        <u-form ref="formRef" :model="data" :rules="rules" class="w-full">
          <u-form-item prop="oldPassword">
            <u-input v-model="data.oldPassword" placeholder="请输入你的旧密码" />
          </u-form-item>
          <u-form-item prop="newPassword">
            <u-input v-model="data.newPassword" placeholder="请输入你的新密码" type="password" />
          </u-form-item>
          <u-form-item prop="confirmPassword">
            <u-input v-model="data.confirmPassword" placeholder="请再次确认你的新密码" type="password" />
          </u-form-item>
        </u-form>
      </view>
    </view>
    <view class="box-border w-full p20rpx">
      <u-button text="修改密码" type="primary" @click="modifyPassword" />
    </view>
  </view>
</template>

<script setup lang='ts' name='user-password'>
import { $url, UserApi } from '@/api';
import type { IModifyPasswordReq } from '@/api/user/type';
import { Toast } from '@/utils';

// 修改密码表单
const data = ref<IModifyPasswordReq>({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});
const formRef = ref<any>(null);
const rules = reactive({
  oldPassword: [
    {
      required: true,
      message: '旧密码不能为空',
      trigger: ['blur'],
    },
  ],
  newPassword: [
    {
      required: true,
      message: '新密码不能为空',
      trigger: ['blur'],
    },
    {
      // 自定义验证密码长度
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          return;
        }
        if (value.length < 6) {
          return callback(new Error('密码长度不能小于6位'));
        }
      },
      trigger: ['blur'],
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: '请再次输入新密码',
      trigger: ['blur'],
    },
    {
      // 自定义验证密码一致性
      validator: (rule: any, value: string, callback: any) => {
        if (!value) {
          return;
        }
        if (value !== data.value.newPassword) {
          return callback(new Error('两次输入的密码不一致'));
        }
      },
      trigger: ['blur'],
    },
  ],
});

// 修改密码
const modifyPassword = () => {
  formRef.value.validate().then((valid: any) => {
    if (valid) {
      UserApi.changePassword(data.value).then(() => {
        Toast('修改密码成功');
        data.value = {
          oldPassword: '',
          newPassword: '',
          confirmPassword: '',
        };
      });
    }
    else {
      uni.$u.toast('修改失败');
    }
  }).catch(() => {
    // 处理验证错误
    uni.$u.toast('修改失败');
  });
};
</script>

  <style lang='scss' scoped>
  .login{
    .backg{
      // unocss写法 bg-gradient-to-b from-[#168BF2] via-[#168BF2] to-white
      // @apply bg-gradient-to-b from-[#168BF2] via-[#168BF2] to-white;
      background: linear-gradient(to bottom, #168BF2 60%, #FFF 100%);
    }
  }
  </style>
